# -*- coding: utf-8 -*-
import json

import logging
import requests
import time
from scrapy.utils.project import get_project_settings


class HttpCommon(object):
    """
        http操作公共类，提供了get与post两种请求方式
    """
    def __init__(self):
        settings = get_project_settings()
        self.url = settings.get('NG_URL')

    @staticmethod
    def static_get_method(url, params):
        r = requests.get(url, params=params)
        return r.url

    @staticmethod
    def static_post_method(url, params):
        # payload = json.dumps(dict(item), ensure_ascii=False)
        # r = requests.post(url, json=payload)
        r = requests.post(url, data=params)
        return r.url

    def get_method(self, params):
        # cookies = dict(cookies_are='working')
        # r = requests.get(self.url, cookies=cookies)
        # 避免因域名解析错误导致日志发送失败，捕获异常并重试
        try:
            r = requests.get(self.url, params=params)
            return r.url
        except Exception as e:
            logging.error("get_method_failed:%s" % e)
            time.sleep(3)
            try:
                r = requests.get(self.url, params=params)
                return r.url
            except Exception as e:
                logging.error("get_method_failed_again:%s" % e)

    def post_method(self, params):
        # payload = json.dumps(dict(item), ensure_ascii=False)
        # r = requests.post(self.url, json=payload)
        # 避免因域名解析错误导致日志发送失败，捕获异常并重试
        try:
            r = requests.post(self.url, data=params)
        except Exception as e:
            logging.error("post_method_exception:%s" % e)
            time.sleep(3)
            r = requests.post(self.url, data=params)
        return r.url



